<template>
  <el-dialog
    v-model="dialogVisible"
    title="分类管理"
    width="800px"
    class="classify-management-dialog"
    :before-close="handleClose"
  >
    <div class="dialog-content">
      <!-- 添加新分类 -->
      <div class="add-section">
        <h3 class="section-title">添加新分类</h3>
        <div class="add-form">
          <el-input
            v-model="newClassifyName"
            placeholder="请输入分类名称"
            class="classify-input"
            @keyup.enter="handleAddClassify"
          >
            <template #prefix>
              <el-icon><FolderOpened /></el-icon>
            </template>
          </el-input>
          <el-input
            v-model="newClassifyValue"
            placeholder="分类值 (英文标识)"
            class="value-input"
          >
            <template #prefix>
              <el-icon><Key /></el-icon>
            </template>
          </el-input>
          <el-input
            v-model="newClassifyDescription"
            placeholder="分类描述 (可选)"
            class="desc-input"
          >
            <template #prefix>
              <el-icon><Document /></el-icon>
            </template>
          </el-input>
          <el-button
            type="primary"
            @click="handleAddClassify"
            class="add-btn"
            :disabled="!newClassifyName.trim() || !newClassifyValue.trim()"
          >
            <el-icon><Plus /></el-icon>
            添加分类
          </el-button>
        </div>
      </div>

      <!-- 分类列表 -->
      <div class="classifies-section">
        <h3 class="section-title">现有分类 ({{ classifies.length }})</h3>
        <div class="classifies-container">
          <div
            v-for="classify in classifies"
            :key="classify.id"
            class="classify-item"
          >
            <div class="classify-info">
              <div class="classify-icon">
                <el-icon><FolderOpened /></el-icon>
              </div>
              <div class="classify-details">
                <div class="classify-name">{{ classify.label }}</div>
                <div class="classify-value">{{ classify.value }}</div>
                <div class="classify-description">{{ classify.description || '暂无描述' }}</div>
              </div>
            </div>
            <div class="classify-actions">
              <el-button
                size="small"
                @click="handleEditClassify(classify)"
                class="edit-btn"
              >
                <el-icon><Edit /></el-icon>
              </el-button>
              <el-button
                size="small"
                type="danger"
                @click="handleDeleteClassify(classify)"
                class="delete-btn"
              >
                <el-icon><Delete /></el-icon>
              </el-button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 编辑分类弹窗 -->
    <el-dialog
      v-model="editDialogVisible"
      title="编辑分类"
      width="500px"
      class="edit-classify-dialog"
      append-to-body
    >
      <div class="edit-form">
        <el-form :model="editingClassify" label-width="100px">
          <el-form-item label="分类名称">
            <el-input v-model="editingClassify.label" placeholder="请输入分类名称" />
          </el-form-item>
          <el-form-item label="分类值">
            <el-input 
              v-model="editingClassify.value" 
              placeholder="请输入分类值"
            />
          </el-form-item>
          <el-form-item label="分类描述">
            <el-input 
              v-model="editingClassify.description" 
              type="textarea"
              :rows="3"
              placeholder="请输入分类描述"
            />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSaveEdit">保存</el-button>
        </div>
      </template>
    </el-dialog>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">关闭</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  FolderOpened,
  Key,
  Document,
  Plus,
  Edit,
  Delete
} from '@element-plus/icons-vue'
import { useClassifies } from '../composables/useClassifies'
import type { Classify, CreateClassifyInput, UpdateClassifyInput } from '../types/classify'

// Props
interface Props {
  modelValue: boolean
}

const props = defineProps<Props>()

// Emits
const emit = defineEmits<{
  'update:modelValue': [value: boolean]
  'classifiesUpdated': [classifies: Classify[]]
}>()

// 使用分类管理composable
const {
  classifies,
  loading,
  error,
  hasError,
  isEmpty,
  fetchClassifies,
  createClassify,
  updateClassify,
  deleteClassify,
  clearError
} = useClassifies()

// 响应式数据
const dialogVisible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

const newClassifyName = ref('')
const newClassifyValue = ref('')
const newClassifyDescription = ref('')
const editDialogVisible = ref(false)
const editingClassify = ref<Partial<Classify>>({
  id: '',
  label: '',
  value: '',
  description: ''
})

// 监听分类状态变化，通知父组件
watch(
  classifies,
  (newClassifies) => {
    emit('classifiesUpdated', newClassifies)
  },
  { deep: true }
)

// 生命周期
onMounted(() => {
  loadClassifies()
})

// 监听对话框显示状态
watch(dialogVisible, (visible) => {
  if (visible) {
    loadClassifies()
  }
})

/**
 * 检查分类名称或值是否已存在
 */
function isNameOrValueExists(name: string, value: string, excludeId?: string): boolean {
  return classifies.value.some(classify => 
    (classify.label === name || classify.value === value) && classify.id !== excludeId
  )
}

/**
 * 加载分类数据
 */
async function loadClassifies() {
  try {
    clearError()
    const result = await fetchClassifies()
    
    if (!result.success && result.error) {
      ElMessage.error(result.error)
    }
  } catch (error) {
    console.error('加载分类数据失败:', error)
    ElMessage.error('加载分类数据失败，请稍后重试')
  }
}

/**
 * 添加新分类
 */
async function handleAddClassify() {
  const trimmedName = newClassifyName.value.trim()
  const trimmedValue = newClassifyValue.value.trim()
  
  if (!trimmedName) {
    ElMessage.warning('请输入分类名称')
    return
  }

  if (!trimmedValue) {
    ElMessage.warning('请输入分类值')
    return
  }

  // 检查分类名称或值是否已存在
  if (isNameOrValueExists(trimmedName, trimmedValue)) {
    ElMessage.warning('分类名称或分类值已存在')
    return
  }

  try {
    const classifyData: CreateClassifyInput = {
      label: trimmedName,
      value: trimmedValue,
      description: newClassifyDescription.value.trim() || ''
    }

    const result = await createClassify(classifyData)
    
    if (result.success) {
      // 清空输入框
      newClassifyName.value = ''
      newClassifyValue.value = ''
      newClassifyDescription.value = ''
      
      ElMessage.success('分类添加成功')
    } else if (result.error) {
      ElMessage.error(result.error)
    }
  } catch (error) {
    console.error('添加分类失败:', error)
    ElMessage.error('添加分类失败，请稍后重试')
  }
}

/**
 * 编辑分类
 */
function handleEditClassify(classify: Classify) {
  editingClassify.value = { ...classify }
  editDialogVisible.value = true
}

/**
 * 保存编辑
 */
async function handleSaveEdit() {
  const trimmedName = editingClassify.value.label?.trim()
  const trimmedValue = editingClassify.value.value?.trim()
  
  if (!trimmedName) {
    ElMessage.warning('请输入分类名称')
    return
  }

  if (!trimmedValue) {
    ElMessage.warning('请输入分类值')
    return
  }

  // 检查分类名称或值是否已存在（排除当前编辑的分类）
  if (isNameOrValueExists(trimmedName, trimmedValue, editingClassify.value.id)) {
    ElMessage.warning('分类名称或分类值已存在')
    return
  }

  try {
    const updateData: UpdateClassifyInput = {
      label: trimmedName,
      value: trimmedValue,
      description: editingClassify.value.description?.trim() || ''
    }

    const result = await updateClassify(editingClassify.value.id, updateData)
    
    if (result.success) {
      editDialogVisible.value = false
      ElMessage.success('分类更新成功')
    } else if (result.error) {
      ElMessage.error(result.error)
    }
  } catch (error) {
    console.error('更新分类失败:', error)
    ElMessage.error('更新分类失败，请稍后重试')
  }
}

/**
 * 删除分类
 */
async function handleDeleteClassify(classify: Classify) {
  try {
    await ElMessageBox.confirm(
      `确定要删除分类 "${classify.label}" 吗？此操作不可恢复。`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    const result = await deleteClassify(classify.id)
    
    if (result.success) {
      ElMessage.success('分类删除成功')
    } else if (result.error) {
      ElMessage.error(result.error)
    }
  } catch (error) {
    if (error === 'cancel') {
      // 用户取消删除，不显示错误信息
      return
    }
    console.error('删除分类失败:', error)
    ElMessage.error('删除分类失败，请稍后重试')
  }
}

/**
 * 关闭对话框
 */
function handleClose() {
  dialogVisible.value = false
}
</script>

<style scoped>
/* 整体对话框内容样式 */
.dialog-content {
  color: rgba(255, 255, 255, 0.9);
  padding: 0;
}

/* 章节标题样式 */
.section-title {
  color: #ffffff;
  font-size: 1.1rem;
  font-weight: 600;
  margin-bottom: 16px;
  padding: 12px 16px;
  background: rgba(255, 255, 255, 0.08);
  border-left: 3px solid rgba(255, 255, 255, 0.3);
  border-radius: 0 4px 4px 0;
}

/* 添加区域样式 */
.add-section {
  margin-bottom: 24px;
  padding: 20px;
  background: rgba(255, 255, 255, 0.05);
  border: 1px solid rgba(255, 255, 255, 0.1);
  border-radius: 4px;
}

.add-form {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 12px;
  margin-top: 16px;
}

.classify-input, .value-input {
  grid-column: span 1;
}

.desc-input {
  grid-column: span 2;
}

.add-btn {
  grid-column: span 2;
  justify-self: end;
  background: rgba(40, 44, 52, 0.9);
  border: 1px solid rgba(255, 255, 255, 0.2);
  border-radius: 4px;
  color: #ffffff;
  font-weight: 500;
  padding: 10px 20px;
  text-transform: uppercase;
  letter-spacing: 0.5px;
}

.add-btn:disabled {
  background: rgba(40, 44, 52, 0.5);
  color: rgba(255, 255, 255, 0.3);
  border-color: rgba(255, 255, 255, 0.1);
}

/* 分类列表区域 */
.classifies-section {
  padding: 20px;
  background: rgba(30, 34, 42, 0.6);
  border: 1px solid rgba(255, 255, 255, 0.1);
  border-radius: 4px;
}

.classifies-container {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
  gap: 16px;
  max-height: 400px;
  overflow-y: auto;
  padding-right: 8px;
}

/* 滚动条样式 */
.classifies-container::-webkit-scrollbar {
  width: 6px;
}

.classifies-container::-webkit-scrollbar-track {
  background: rgba(0, 0, 0, 0.2);
  border-radius: 3px;
}

.classifies-container::-webkit-scrollbar-thumb {
  background: rgba(255, 255, 255, 0.2);
  border-radius: 3px;
}

/* 分类项样式 */
.classify-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 18px;
  background: rgba(20, 24, 32, 0.9);
  border: 1px solid rgba(50, 236, 138, 0.3);
  border-radius: 4px;
  margin-bottom: 8px;
}

.classify-info {
  display: flex;
  align-items: center;
  gap: 16px;
  flex: 1;
}

.classify-icon {
  width: 24px;
  height: 24px;
  color: #32ec8a;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 4px;
  background: rgba(50, 236, 138, 0.15);
  border: 1px solid rgba(50, 236, 138, 0.3);
  flex-shrink: 0;
}

.classify-details {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.classify-name {
  color: #ffffff;
  font-weight: 600;
  font-size: 1.05rem;
  margin: 0;
}

.classify-value {
  color: #32ec8a;
  font-size: 0.9rem;
  font-weight: 500;
  font-family: 'Courier New', monospace;
}

.classify-description {
  color: rgba(255, 255, 255, 0.7);
  font-size: 0.85rem;
  line-height: 1.4;
  margin-top: 2px;
}

.classify-stats {
  display: flex;
  align-items: center;
  margin-right: 12px;
}

.classify-status {
  color: rgba(255, 255, 255, 0.9);
  font-size: 0.85rem;
  font-weight: 500;
  background: rgba(220, 70, 70, 0.2);
  padding: 4px 10px;
  border-radius: 3px;
  border: 1px solid rgba(220, 70, 70, 0.4);
  white-space: nowrap;
}

.classify-status.active {
  background: rgba(50, 236, 138, 0.2);
  border: 1px solid rgba(50, 236, 138, 0.4);
  color: rgba(255, 255, 255, 0.9);
}

/* 操作按钮样式 */
.classify-actions {
  display: flex;
  gap: 8px;
  align-self: flex-end;
}

.edit-btn {
  background: rgba(70, 130, 180, 0.2);
  border: 1px solid rgba(70, 130, 180, 0.4);
  color: #70a0d0;
  border-radius: 3px;
  padding: 6px 10px;
}

.delete-btn {
  background: rgba(220, 70, 70, 0.2);
  border: 1px solid rgba(220, 70, 70, 0.4);
  color: #e07070;
  border-radius: 3px;
  padding: 6px 10px;
}

/* 底部按钮区域 */
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 16px;
  padding: 16px 20px;
  background: rgba(50, 236, 138, 0.05);
  border-top: 1px solid rgba(50, 236, 138, 0.2);
  border-radius: 0 0 4px 4px;
}

.edit-form {
  padding: 20px 0;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .add-form {
    grid-template-columns: 1fr;
    gap: 12px;
  }
  
  .classify-input,
  .value-input,
  .desc-input,
  .add-btn {
    grid-column: span 1;
  }
  
  .classifies-container {
    grid-template-columns: 1fr;
  }
  
  .classify-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }
  
  .classify-actions {
    align-self: flex-end;
    width: 100%;
    justify-content: flex-end;
  }
}
</style>